package com.mywang.weitravel.net.interceptor;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.EOFException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

import okhttp3.Connection;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.http.HttpHeaders;
import okhttp3.internal.platform.Platform;
import okio.Buffer;
import okio.BufferedSource;
import okio.GzipSource;

public class HttpLoggingInterceptor implements Interceptor {
    private final static String LINE_SEPARATOR = System.getProperty("line.separator");
    private final static Charset UTF8 = Charset.forName("UTF-8");
    private Logger logger;

    public interface Logger {
        void log(String message);

        Logger DEFAULT = new Logger() {

            private synchronized void printLine(boolean isTop) {
                if (isTop) {
                    Platform.get().log(Platform.INFO, "╔═══════════════════════════════════════════════════════════════════════════════════════", null);

                } else {
                    Platform.get().log(Platform.INFO, "╚═══════════════════════════════════════════════════════════════════════════════════════", null);
                }
            }

            @Override
            public void log(String message) {
                printLine(true);
                String[] lines = message.split(LINE_SEPARATOR);
                for (String line : lines) {
                    Platform.get().log(Platform.INFO, "║ " + line, null);
                }
                printLine(false);
            }
        };
    }

    public HttpLoggingInterceptor() {
        this(Logger.DEFAULT);
    }

    public HttpLoggingInterceptor(Logger logger) {
        this.logger = logger;
    }

    @Override
    public synchronized Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        RequestBody requestBody = request.body();
        boolean hasRequestBody = requestBody != null;

        Connection connection = chain.connection();

        StringBuilder requestStartMessage = new StringBuilder("--> "
                + request.method()
                + ' ' + request.url()
                + (connection != null ? " " + connection.protocol() : ""));

        if (hasRequestBody) {
            requestStartMessage.append(" (").append(requestBody.contentLength()).append("-byte body)");

            if (requestBody.contentType() != null) {
                requestStartMessage.append(LINE_SEPARATOR).append("Content-Type: ").append(requestBody.contentType());
            }

            if (requestBody.contentLength() != -1) {
                requestStartMessage.append(LINE_SEPARATOR).append("Content-Length: ").append(requestBody.contentLength());
            }
        }

        Headers headers = request.headers();
        for (int i = 0, count = headers.size(); i < count; ++i) {
            String name = headers.name(i);
            if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                requestStartMessage.append(LINE_SEPARATOR).append(headers.name(i)).append(": ").append(headers.value(i));
            }
        }

        if (!hasRequestBody) {
            // requestStartMessage.append(LINE_SEPARATOR).append("--> END ").append(request.method());
        } else if (bodyHasUnknownEncoding(request.headers())) {
            // requestStartMessage.append(LINE_SEPARATOR).append("--> END ").append(request.method()).append(" (encoded body omitted)");
        } else {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }

            requestStartMessage.append(LINE_SEPARATOR).append("");
            if (isPlaintext(buffer)) {
                requestStartMessage.append(LINE_SEPARATOR)
                        .append(buffer.readString(charset));
                requestStartMessage.append(LINE_SEPARATOR)
                        .append("--> END ")
                        .append(request.method())
                        .append(" (")
                        .append(requestBody.contentLength())
                        .append("-byte body)");
            } else {
                requestStartMessage.append(LINE_SEPARATOR)
                        .append("--> END ")
                        .append(request.method())
                        .append(" (binary ")
                        .append(requestBody.contentLength())
                        .append("-byte body omitted)");
            }
        }

        long startNs = System.nanoTime();
        Response response;
        try {
            response = chain.proceed(request);
        } catch (Exception e) {
            requestStartMessage
                    .append(LINE_SEPARATOR)
                    .append("<-- HTTP FAILED: ").append(e);
            throw e;
        }

        ResponseBody responseBody = response.body();
        long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
        long contentLength = responseBody.contentLength();
        String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
        requestStartMessage
                .append(LINE_SEPARATOR)
                .append("<-- ")
                .append(response.code())
                .append(response.message().isEmpty() ? "" : ' ' + response.message())
                .append(' ')
                .append(response.request().url())
                .append(" (")
                .append(tookMs)
                .append("ms")
                .append(", ")
                .append(bodySize)
                .append(" body")
                .append(')');

        Headers responseHeaders = response.headers();
        for (int i = 0, count = responseHeaders.size(); i < count; i++) {
            requestStartMessage
                    .append(LINE_SEPARATOR)
                    .append(responseHeaders.name(i))
                    .append(": ")
                    .append(responseHeaders.value(i));
        }
        if (!HttpHeaders.hasBody(response)) {
            requestStartMessage
                    .append(LINE_SEPARATOR)
                    .append("<-- END HTTP");
        } else if (bodyHasUnknownEncoding(response.headers())) {
            requestStartMessage
                    .append(LINE_SEPARATOR)
                    .append("<-- END HTTP (encoded body omitted)");
        } else {
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();

            Long gzippedLength = null;
            if ("gzip".equalsIgnoreCase(headers.get("Content-Encoding"))) {
                gzippedLength = buffer.size();
                try (GzipSource gzippedResponseBody = new GzipSource(buffer.clone())) {
                    buffer = new Buffer();
                    buffer.writeAll(gzippedResponseBody);
                }
            }

            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }

            if (!isPlaintext(buffer)) {
                requestStartMessage
                        .append(LINE_SEPARATOR)
                        .append("");
                requestStartMessage
                        .append(LINE_SEPARATOR)
                        .append("<-- END HTTP (binary ")
                        .append(buffer.size())
                        .append("-byte body omitted)");
                return response;
            }

            if (contentLength != 0) {
                requestStartMessage
                        .append(LINE_SEPARATOR)
                        .append("");

                String msg = buffer.clone().readString(charset);

                try {
                    if (msg.startsWith("{")) {
                        JSONObject jsonObject = new JSONObject(msg);
                        requestStartMessage
                                .append(LINE_SEPARATOR)
                                .append(jsonObject.toString(4));//最重要的方法，就一行，返回格式化的json字符串，其中的数字4是缩进字符数
                    } else if (msg.startsWith("[")) {
                        JSONArray jsonArray = new JSONArray(msg);
                        requestStartMessage
                                .append(LINE_SEPARATOR)
                                .append(jsonArray.toString(4));
                    } else {
                        requestStartMessage
                                .append(LINE_SEPARATOR)
                                .append(msg);
                    }
                } catch (JSONException e) {
                    requestStartMessage
                            .append(LINE_SEPARATOR)
                            .append(msg);
                }
            }

            if (gzippedLength != null) {
                requestStartMessage
                        .append(LINE_SEPARATOR)
                        .append("<-- END HTTP (")
                        .append(buffer.size())
                        .append("-byte, ")
                        .append(gzippedLength)
                        .append("-gzipped-byte body)");
            } else {
                requestStartMessage
                        .append(LINE_SEPARATOR)
                        .append("<-- END HTTP (")
                        .append(buffer.size())
                        .append("-byte body)");
            }
        }

        logger.log(requestStartMessage.toString());
        return response;
    }

    private boolean isPlaintext(Buffer buffer) {
        try {
            Buffer prefix = new Buffer();
            long byteCount = buffer.size() < 64 ? buffer.size() : 64;
            buffer.copyTo(prefix, 0, byteCount);
            for (int i = 0; i < 16; i++) {
                if (prefix.exhausted()) {
                    break;
                }
                int codePoint = prefix.readUtf8CodePoint();
                if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
                    return false;
                }
            }
            return true;
        } catch (EOFException e) {
            return false; // Truncated UTF-8 sequence.
        }
    }

    private boolean bodyHasUnknownEncoding(Headers headers) {
        String contentEncoding = headers.get("Content-Encoding");
        return contentEncoding != null
                && !contentEncoding.equalsIgnoreCase("identity")
                && !contentEncoding.equalsIgnoreCase("gzip");
    }
}
